<template>
    <div class="container">
        <div class="mapContainer" :style="mapWindowStyle">
            <l-map class="map" ref="map" :options="mapOptions" @click="showLatLng"
                   @update:zoom="zoomUpdated"
                   @update:center="centerUpdated"
                   @update:bounds="boundsUpdated"
            > <!-- IMPORTANT PART HERE -->
                <!--<v-geosearch :options="geosearchOptions" ></v-geosearch>-->
                <!-- /IMPORTANT PART HERE -->
                <!--<l-control-layers position="topleft" :sortLayers="true" :sortFunction="sortMapLayer"></l-control-layers>-->
                <l-tile-layer ref="satelite" :url="layers.satellite.url" :options="layers.satellite.options" layer-type="base" name="卫星底图"></l-tile-layer>
                <l-control position="topleft" v-show="search.searchPanelVisable" >

                    <el-input v-show="search.searchVisable" placeholder="请输入城市或国家名" v-model="search.searchCityValue" class="input-with-select">
                        <el-button slot="prepend" icon="el-icon-circle-close" v-on:click="search.searchVisable = false" title="点击隐藏"></el-button>
                        <el-button slot="append" icon="el-icon-search" v-on:click="mapSearchCallBack(search.searchCityValue)" title="立即搜索"></el-button>
                    </el-input>
                    <el-button v-show="!search.searchVisable" icon="el-icon-search" v-on:click="search.searchVisable = true" title="点击显示城市搜索"></el-button>
                </l-control>
                <l-geo-json
                        :geojson="this.layers.geolayers.administrative_regions.geojson"
                        :options="options"
                        :options-style="styleFunction"
                        :visible="this.layers.geolayers.visible"
                        layer-type="overlay"
                        name="行政区域"
                />
                <l-layer-group ref="marker_features"
                               layer-type="overlay"
                               name="标记点集合">
                    <v-marker-cluster ref="clusterRef" :options="marker_cluster_options">

                    <l-marker
                            style="position: relative;"
                            v-for="(marker,index) in markers"
                            :key="marker.index"
                            :visible="marker.visible"
                            :draggable="marker.draggable"
                            :lat-lng.sync="marker.position"
                            @click="markerClick(marker.id , $event)"
                    >
                        <l-icon :icon-size="marker.icon.iconSize" :icon-url="marker.icon.iconUrl"
                                :icon-anchor="marker.icon.iconAnchor"
                                :shadow-size="marker.icon.shadowSize" :shadow-url="marker.icon.shadowUrl"
                                :shadow-anchor="marker.icon.shadowAnchor"
                                :popup-anchor="marker.icon.popupAnchor"/>
                        <l-popup v-if="marker.tooltip!=''" :content="marker.tooltip"></l-popup>
                    </l-marker>
                    </v-marker-cluster>
                </l-layer-group>
                <l-control :position="'topright'" class="example-custom-control">
                    <div class="layermanager-nav">
                        <div class="layermanager"><img  class="layermanager-img"  :src="control_btns.btnLayerManager.ico" title="功能选择"/>
                            <span :class="control_btns.btnLayerManager.managercss"  @click="changeLayer"
                                  title="包含热力图、鹰眼图和飞线图等功能">功能选择
                            </span>
                        </div>
                        <img class="layermanager-img-left" @click="showtoolbox" :src="control_btns.btnToolBox.ico" :title="control_btns.btnToolBox.title"/>

                    </div>
                    <el-card class="box-card" v-if="this.layers_panel_visable">
                        <el-switch
                                v-model="layers.heatmapLayer.visible"
                                @change="showheatmap"
                                :active-color="theme.theme_activecolor">
                        </el-switch>&nbsp;&nbsp;<span :class='theme.theme_textcolor' style="vertical-align:middle;">显示热力图</span>
                        <br><br>
                        <el-switch
                                v-model="layers.eye.visible"
                                @change="showeyemap"
                                :active-color="theme.theme_activecolor">
                        </el-switch>&nbsp;&nbsp;<span :class='theme.theme_textcolor' style="vertical-align:middle;">显示鹰眼图</span>

                        <br><br>
                        <el-switch
                                v-model="layers.flyLayer.visible"
                                @change="showflymap"
                                :active-color="theme.theme_activecolor">
                        </el-switch>&nbsp;&nbsp;<span :class='theme.theme_textcolor' style="vertical-align:middle;">显示飞线图</span>
                    </el-card>
                </l-control>

                <l-control :position="'bottomright'" class="example-custom-control">
                    <div class="right_control">
                        <img class="item" @click="showheatmap" :src="control_btns.btnHeat.ico" :title="control_btns.btnHeat.title"/>
                        <img class="item" @click="showeyemap" :src="control_btns.btnEye.ico" :title="control_btns.btnEye.title"/>
                        <img class="item" @click="zoomIn" :src="control_btns.btnZoomIn.ico" :title="control_btns.btnZoomIn.title" style="margin-bottom:0px;"/>
                        <img class="item" @click="zoomOut" :src="control_btns.btnZoomOut.ico" :title="control_btns.btnZoomOut.title"/>
                        <img class="item" @click="toggleFullScreen()" :src="control_btns.btnFullScreen.ico" :title="control_btns.btnFullScreen.title"/>
                    </div>
                </l-control>

                <l-control :position="'bottomleft'" class="example-custom-control">
                    <div class="legend-loading" v-show="loadingText!=''">{{loadingText}}...</div>
                    <div class="legend-area" v-show="this.layers.heatmapLayer.visible">
                        <h4>热力图图例</h4>
                        <span id="min">{{heatLegend.min}}</span>
                        <span id="max">{{heatLegend.max}}</span>
                        <img  :src="heatLegend.gradientImg" style="width:300px" />
                    </div>
                </l-control>
            </l-map>
        </div>
    </div>
</template>

<script>
    import * as L from 'leaflet'
    import 'wgis.leaflet.wmts.vue2';
    import 'wgis.leaflet.migration.vue2';
    import MiniMap from "leaflet-minimap";
    import {
        LControl,
        LGeoJson,
        LPopup,
        LIcon,
        DomEvent,
        DomUtil,
        LControlLayers,
        LLayerGroup,
        LCircle
    } from "wgis.leaflet.vue2";
    import HeatmapOverlay from 'heatmap.js/plugins/leaflet-heatmap'
    import omnivore from 'leaflet-omnivore'
    import csv2geojson from 'csv2geojson'
    import toGeoJSON from 'togeojson'
    import 'leaflet-draw';
    import { OpenStreetMapProvider } from 'wgis.leaflet.geosearch.vue2';
    import  MyProvider from '../provider/MyProvider.js'
    import VGeosearch from '../components/Vue2LeafletGeosearch.vue';
    import Vue2LeafletMarkerCluster from 'vue2-leaflet-markercluster'


    const GEO_SERVER_URL = process.env.GEO_SERVER_URL
    export default {
        name: 'MapClassification',
        components: {
            LControl,LGeoJson,LPopup,LIcon,LControlLayers,LLayerGroup,VGeosearch,
            'v-marker-cluster': Vue2LeafletMarkerCluster

        },
        data() {
            return {
                //主题色
                theme:{
                    color:"green",
                    theme_textcolor:"theme_green",
                    theme_activecolor: "#3bc96a",
                },
                //地图参数
                mapOptions:{
                    attributionControl :false,
                    zoomControl:false,
                    minZoom: 2,
                    maxZoom: 14,
                    zoom: 5,
                    center: {'lon':113.65,'lat':34.77},
                    preferCanvas: true
                },
                map: null,
                //图层
                map_layers:{

                },
                search:{
                    searchPanelVisable:false,//搜索面板是否显示
                    searchCityValue:"",//搜索城市
                    searchVisable:false
                },
                geosearchOptions: { // Important part Here
                    provider: new OpenStreetMapProvider(),
                    searchLabel: '输入城市',
                    showMarker: true,

                },
                //层管理
                layers_panel_visable:false,
                //层集合
                layers:{
                    satellite: {
                        url: GEO_SERVER_URL + "/gwc/service/tms/1.0.0/China@EPSG%3A3857@jpeg/{z}/{x}/{-y}.jpeg",
                        options:{
                            minZoom: 2,
                            maxZoom: 14,
                            opacity:0.5,
                        },
                    },
                    eye:{
                        instance:null,
                        url: GEO_SERVER_URL + "/gwc/service/tms/1.0.0/China@EPSG%3A3857@jpeg/{z}/{x}/{-y}.jpeg",
                        options:{
                            minZoom: 2,
                            maxZoom: 14,
                            position: 'bottomleft',
                            width: 200,
                            height: 175,
                        },
                        visible:false
                    },
                    //热力图
                    heatmapLayer: {
                        instance:null,
                        heatmapcfg : //热力图配置
                            {
                                '/': 0.191,
                                'maxOpacity': 0.8,
                                'scaleRadius': true,
                                'useLocalExtrema': true,
                                latField: 'lat',
                                lngField: 'lng',
                                valueField: 'count',

                            },
                        heatmapData://热力图数据
                            {
                                max: 0,
                                data: [
                                ]
                            },
                        visible:false
                    },
                    //飞线图
                    flyLayer: {
                        instance:null,
                        flycfg : //飞线图配置
                            {
                                pulseRadius: 10,
                                arcWidth: 3,
                                label: true,
                                order: false,
                               /* replacePopover: function (x, y, data, index) {
                                    console.log(x, y, data, index, 'show popover');
                                    that.popover.innerHTML = '被攻击方:' + data.labels[1] + '<br> 攻击方:' + data.labels[0] + "<br> 次数:" + data.value
                                    return that.popover;
                                },
                                onHidePopover: function (index) {
                                    console.log('hide popover', index);
                                }*/
                            },
                        flyData://飞线图数据
                            [

                            ],
                        visible:false
                    },
                    //geojson层
                    geolayers: {
                        visable:false,
                        administrative_regions:{
                            geojson:null,
                            cfg:{
                                layer_name:'',//图层后台名
                                source:'省',
                                filter_col_name:'',//过滤列名称
                                show_col_name:''//显示列名称
                            },
                            style:{
                                weight: 2, //轮廓粗细
                                color: '#3bc96a', //轮廓颜色
                                opacity: 1,//透明度
                                fillColor: '#3bc96a', //内部填充的颜色
                                fillOpacity: 0.2 //内部填充的透明度
                            },
                            tpl:{
                                tipHtml:"<div>{{GIS_XZ_NAME}}</div>" ,//tip模板html
                                popHtml:"<div>弹出：{{GIS_XZ_NAME}}</div>" ,//弹出模板html
                            }
                        }

                    }
                },
                //工具管理
                measure_toolbox:{
                    instance:null,
                    options:{
                        position: 'topleft',
                        draw: {
                            polyline: {
                                shapeOptions: {
                                    color: '#f357a1',
                                    weight: 10
                                }
                            },
                            polygon: {
                                allowIntersection: false, // Restricts shapes to simple polygons
                                drawError: {
                                    color: '#e1e100', // Color the shape will turn when intersects
                                    message: '<strong>操作有误!<strong>  操作有误!' // Message that will show when intersect
                                },
                                shapeOptions: {
                                    color: '#bada55'
                                }
                            },
                            circle: false, // Turns off this drawing tool
                            rectangle: {
                                shapeOptions: {
                                    clickable: true
                                }
                            },
                            marker: {

                            }
                        },
                        edit: {
                            featureGroup: null, //REQUIRED!!
                            remove: true
                        }
                    },
                    visible:false

                },
                //工具管理
                mapWindowStyle: {
                    height: '100px'
                },
                //全屏开关
                fullscreen: false,

                //模拟点位置
                debug_count :0,
                //点相关
                markers: [],
                marker_cluster_options:{singleMarkerMode:true,maxClusterRadius:50,spiderLegPolylineOptions: {opacity: 0} },
                //热力图绘图相关
                heatLegend:{
                    legendCanvas:null,
                    legendCtx:null,
                    gradientCfg:null,
                    gradientImg:null,
                    min:0,
                    max:0
                },
                loadingText:''//加载中提示
            }
        },

        methods: {
            getHeight() {
                this.mapWindowStyle.height = String(window.innerHeight) + 'px';
            },
            showLatLng(e){
                let data = {
                    'lat':e.latlng.lat,
                    'lng':e.latlng.lng,
                }
                this.handleMessageToParent("RE1005",data);
                console.log(e.latlng);
            },
            changeLayer(e){
                console.log(e)
                this.layers_panel_visable = !this.layers_panel_visable
            },
            zoomIn(){
                this.$refs.map.mapObject.zoomIn();
            },
            zoomOut(){
                this.$refs.map.mapObject.zoomOut();
            },
            //设置基础控件能力
            setBaseComponent(data){
                switch (data.basetype) {
                    //矢量图层
                    case "VectorLayers":
                        switch (data.childtype) {
                            case 'circle':
                                var v_circel =L.circle( data.latlng,data.options);
                                v_circel.addTo(this.$refs.map.mapObject);
                                break;
                            case 'polyline':
                                var v_polyline =L.polyline( data.latlngs,data.options);
                                v_polyline.addTo(this.$refs.map.mapObject);
                                this.$refs.map.mapObject.fitBounds(v_polyline.getBounds());
                                break;
                            case 'polygon':
                                var v_polygon =L.polygon( data.latlngs,data.options);
                                v_polygon.addTo(this.$refs.map.mapObject);
                                this.$refs.map.mapObject.fitBounds(v_polygon.getBounds());
                                break;
                            case 'rectangle':
                                var v_rectangle =L.rectangle( data.latlngs,data.options);
                                v_rectangle.addTo(this.$refs.map.mapObject);
                                this.$refs.map.mapObject.fitBounds(v_rectangle.getBounds());
                                break;
                        }
                        break;
                    //栅格图层
                    case 'RasterLayers':
                        switch (data.childtype) {
                            case 'videooverlay':
                                var v_videooverlay =L.videoOverlay( data.options.videoUrl, data.options.videoBounds);
                                v_videooverlay.addTo(this.$refs.map.mapObject);
                                this.$refs.map.mapObject.fitBounds(v_videooverlay.getBounds());
                                break;
                            case 'imageoverlay':
                                var v_imageoverlay =L.imageOverlay( data.options.imageUrl, data.options.imageBounds);
                                v_imageoverlay.addTo(this.$refs.map.mapObject);
                                this.$refs.map.mapObject.fitBounds(v_imageoverlay.getBounds());
                                break;
                        }
                        break;
                }
            },
            //设置图层关闭
            setcloselayer(data){
                switch (data.cfg.layertype) {
                    case 'fly' :
                        this.layers.flyLayer.visible = !this.layers.flyLayer.visible;
                        if(this.layers.flyLayer.instance != null){
                            this.$refs.map.mapObject.removeLayer(this.layers.flyLayer.instance);
                        }
                        break;
                    case 'heatmap' :
                        this.layers.heatmapLayer.visible = !this.layers.heatmapLayer.visible;
                        if(this.layers.heatmapLayer.instance != null){
                            this.$refs.map.mapObject.removeLayer(this.layers.heatmapLayer.instance);
                        }
                        break;
                }
            },
            //设置卫星图透明度
            setsalelayer(data){
                console.log(this.$refs.satelite)
                this.layers.satellite.options.opacity = data.opacity;
                this.$refs.satelite.setRedrawComponent();
            },
            //显示geojson
            async showgeojson(data){

                let url = GEO_SERVER_URL + '/China/ows?service=WFS&version=1.0.0&request=GetFeature';
                url+='&maxFeatures=50'
                let format_type = 'geojson'
                if(data.cfg.outformat){
                    format_type = data.cfg.outformat
                }
                switch (format_type) {
                    case 'geojson' :  url+='&outputFormat='+encodeURIComponent('application/json') ;break;
                    case 'csv' :  url+='&outputFormat='+encodeURIComponent('CSV') ;break;
                    case 'kml': url+='&outputFormat='+encodeURIComponent('application/vnd.google-earth.kml+xml') ;break;
                    case 'gml':
                        url+='&outputFormat='+encodeURIComponent('text/xml') ;
                        url+='&subtype='+encodeURIComponent('gml/2.1.2') ;break;
                }
                let spec_code = '';
                switch (data.cfg.source) {
                    case '省' :
                        this.layers.geolayers.administrative_regions.cfg.filter_col_name = data.cfg.source+"代码";
                        this.layers.geolayers.administrative_regions.cfg.show_col_name = data.cfg.source;
                        this.layers.geolayers.administrative_regions.cfg.layer_name = 'China:sheng';
                        break;
                    case '市' :
                        this.layers.geolayers.administrative_regions.cfg.filter_col_name = data.cfg.source+"代码";
                        this.layers.geolayers.administrative_regions.cfg.show_col_name = data.cfg.source;
                        this.layers.geolayers.administrative_regions.cfg.layer_name = 'China:shi';
                        break;
                    case '县' :
                        this.layers.geolayers.administrative_regions.cfg.filter_col_name = "PAC";
                        this.layers.geolayers.administrative_regions.cfg.show_col_name = "NAME";
                        this.layers.geolayers.administrative_regions.cfg.layer_name = 'China:xian';
                        break;

                }
                //源地址
                url+='&typeName='+encodeURIComponent(this.layers.geolayers.administrative_regions.cfg.layer_name);
                //过滤器
                url+='&cql_filter='+ encodeURIComponent("\""+this.layers.geolayers.administrative_regions.cfg.filter_col_name+"\"="+data.filter.code);

                this.loadingText = '准备获取数据请稍等';
                console.log(url)
                const response = await fetch(url);

                this.loadingText = '获取完成,准备渲染数据';

                switch (format_type) {
                    //geojson已支持
                    case 'geojson' : this.layers.geolayers.administrative_regions.geojson = await response.json();;break;
                    case 'csv' :
                        var csvStr = await response.text();
                        var that = this
                        //console.log(csvStr);
                        var layer = this.layers.geolayers.administrative_regions.geojson;
                        var onparse = (function (err,geojson) {
                            console.log(geojson);

                            that.layers.geolayers.administrative_regions.geojson  = geojson;
                            console.log(that.layers.geolayers.administrative_regions.geojson);
                        });
                        var geoJson1 = csv2geojson.csv2geojson(csvStr, onparse);
                        console.log('geoJson1',geoJson1 );
                        console.log('geojson',this.layers.geolayers.administrative_regions.geojson );
                        //this.layers.geolayers.administrative_regions.geojson = geoJson1 ;
                       break;
                    //kml已支持
                    case 'kml' :
                        let xml = (new DOMParser()).parseFromString(await response.text(), 'text/xml');
                        this.layers.geolayers.administrative_regions.geojson = toGeoJSON.kml(xml);
                        break;
                    case 'gml' :
                        var gmlStr = await response.text();
                        var that = this
                        //console.log(csvStr);
                        var layer = this.layers.geolayers.administrative_regions.geojson;
                        var onparsegml = (function (err,geojson) {
                            console.log(geojson);
                        });
                        var geoJson1 = gmlToGenJson(csvStr, onparsegml);
                        //
                        break;
                        //outputFormat=text/xml; subtype=gml/2.1.2
                }
                this.layers.geolayers.administrative_regions.cfg.source = data.cfg.source;
                this.layers.geolayers.administrative_regions.style = data.style;
                this.layers.geolayers.administrative_regions.tpl.tipHtml = data.tpl.tipHtml;
                this.layers.geolayers.administrative_regions.tpl.popHtml = data.tpl.popHtml;
                console.log('geojson',this.layers.geolayers.administrative_regions.geojson );
                this.loadingText = '';
            },
            testcall(){
                console.log('sfasdf')
            },
            //显示热力图
            async showheatmap(e){
                console.log(typeof e);
                console.log(this.$refs.map.mapObject);
                if(typeof e != "boolean"){
                    console.log("不是从功能面板过来")
                    this.layers.heatmapLayer.visible = !this.layers.heatmapLayer.visible;
                }
                if(this.layers.heatmapLayer.instance != null){
                    /*这个方法是在每一次刷新热力图之前把前一次创建的热力图对象清除,
                     *如果不对这个对象进行重置，会在每一刷新的时候给这个对象添加数据上去，
                     *会导致这个对象内存增长
                     */
                    this.$refs.map.mapObject.removeLayer(this.layers.heatmapLayer.instance);
                }
                if(this.layers.heatmapLayer.visible == true){
                    this.layers.heatmapLayer.instance = new HeatmapOverlay(this.layers.heatmapLayer.heatmapcfg)
                    this.layers.heatmapLayer.instance.setData(this.layers.heatmapLayer.heatmapData)
                    this.layers.heatmapLayer.instance.addTo(this.$refs.map.mapObject);//添加到地图上
                    console.log(this.$refs.map);
                }
            },
            //必须显示热力图
            showheatmapset(e){

                this.layers.heatmapLayer.visible = true;
                if(this.layers.heatmapLayer.instance != null){
                    /*这个方法是在每一次刷新热力图之前把前一次创建的热力图对象清除,
                     *如果不对这个对象进行重置，会在每一刷新的时候给这个对象添加数据上去，
                     *会导致这个对象内存增长
                     */
                    this.$refs.map.mapObject.removeLayer(this.layers.heatmapLayer.instance);
                }

                this.layers.heatmapLayer.instance = new HeatmapOverlay(this.layers.heatmapLayer.heatmapcfg)
                this.layers.heatmapLayer.instance.setData(this.layers.heatmapLayer.heatmapData)
                this.layers.heatmapLayer.instance.addTo(this.$refs.map.mapObject);//添加到地图上
            },
            //鹰眼图
            showeyemap(e){
                if(typeof e != "boolean"){
                    this.layers.eye.visible = !this.layers.eye.visible;
                }

                if(this.layers.eye.instance != null){
                    this.$refs.map.mapObject.removeControl(this.layers.eye.instance);
                }
                if(this.layers.eye.visible == true){
                    this.layers.eye.instance = new MiniMap(new L.tileLayer(this.layers.eye.url,this.layers.eye.options), {
                        toggleDisplay: true
                    });
                    this.layers.eye.instance.addTo(this.$refs.map.mapObject);//添加到地图上
                }


            },
            //显示飞线图
            showflymap(e){
                console.log(typeof e);
                if(typeof e != "boolean"){

                    console.log("不是从功能面板过来")
                    console.log(e.data.data);
                    console.log(e.data.data.visable);
                    console.log(typeof(e.data.data.visable) !='undefined');
                    if(( e.data !=undefined &&  typeof(e.data.data.visable) !='undefined')){
                        this.layers.flyLayer.visible = e.data.data.visable; 
                    }
                   
                }
                if(this.layers.flyLayer.instance != null){
                    /*这个方法是在每一次刷新fly图之前把前一次创建的fly图对象清除,
                     *如果不对这个对象进行重置，会在每一刷新的时候给这个对象添加数据上去，
                     *会导致这个对象内存增长
                     */
                    this.$refs.map.mapObject.removeLayer(this.layers.flyLayer.instance);
                }
                if(this.layers.flyLayer.visible == true){
                    this.layers.flyLayer.instance = L.migrationLayer(this.layers.flyLayer.flyData.map(i => Object.assign(i, {  })), this.layers.flyLayer.flycfg);
                    this.layers.flyLayer.instance.addTo(this.$refs.map.mapObject);//添加到地图上
                }
            },
            showtoolbox(){
                if( this.measure_toolbox.options.edit.featureGroup !=null){
                    this.$refs.map.mapObject.removeLayer(this.measure_toolbox.options.edit.featureGroup);
                }
                if(this.measure_toolbox.instance != null){
                    this.$refs.map.mapObject.removeControl(this.measure_toolbox.instance);
                }
                if(this.measure_toolbox.visible == true) {
                    this.measure_toolbox.visible = false;
                    return;
                }
                /**语言设置**/
                L.drawLocal.draw.toolbar.buttons.rectangle = '矩形';
                L.drawLocal.draw.toolbar.buttons.marker = '图标';
                L.drawLocal.draw.toolbar.buttons.circlemarker = '圆图标';
                L.drawLocal.draw.toolbar.buttons.polyline = '折线';
                L.drawLocal.draw.toolbar.buttons.circle = '圆形';
                L.drawLocal.draw.toolbar.buttons.polygon = '多边形';

                L.drawLocal.draw.toolbar.finish.title = "完成绘制";
                L.drawLocal.draw.toolbar.finish.text = "完成";
                L.drawLocal.draw.toolbar.actions.title = "取消绘制";
                L.drawLocal.draw.toolbar.actions.text = "取消";
                L.drawLocal.draw.toolbar.undo.title = "撤销上一个点";
                L.drawLocal.draw.toolbar.undo.text = "撤销";

                L.drawLocal.draw.handlers.circle.tooltip = "点击拖拽一个圆";
                L.drawLocal.draw.handlers.circlemarker.tooltip = "点击生成圆图标";
                L.drawLocal.draw.handlers.marker.tooltip = "点击生成图标";
                L.drawLocal.draw.handlers.polygon.tooltip.start = "点击开始绘制图形";
                L.drawLocal.draw.handlers.polygon.tooltip.cont = "点击继续绘制图形";
                L.drawLocal.draw.handlers.polygon.tooltip.end = "点击第一个点结束绘制图形";
                L.drawLocal.draw.handlers.polyline.tooltip.start = "点击开始绘制线";
                L.drawLocal.draw.handlers.polyline.tooltip.cont = "点击继续绘制线";
                L.drawLocal.draw.handlers.polyline.tooltip.end = "点击最后点结束绘制线";
                L.drawLocal.draw.handlers.polyline.error = "<strong>操作有误:</strong> 图形边界不能交叉!";
                L.drawLocal.draw.handlers.rectangle.tooltip.start = "点击开始绘制矩形";
                L.drawLocal.draw.handlers.simpleshape.tooltip.end  = "释放鼠标结束绘制";

                L.drawLocal.edit.toolbar.actions.save.title = "保存更改";
                L.drawLocal.edit.toolbar.actions.save.text = "保存";
                L.drawLocal.edit.toolbar.actions.cancel.title = "取消更改，放弃所有刚刚的更改";
                L.drawLocal.edit.toolbar.actions.cancel.text = "取消";
                L.drawLocal.edit.toolbar.actions.clearAll.title = "清除所有已绘制的图层";
                L.drawLocal.edit.toolbar.actions.clearAll.text = "清除所有";

                L.drawLocal.edit.toolbar.buttons.edit = "编辑";
                L.drawLocal.edit.toolbar.buttons.editDisabled = "无可编辑图层";
                L.drawLocal.edit.toolbar.buttons.remove = "删除图层";
                L.drawLocal.edit.toolbar.buttons.removeDisabled = "无可删除图层";

                L.drawLocal.edit.handlers.edit.tooltip.text = "拖动鼠标或者标记元素.";
                L.drawLocal.edit.handlers.edit.tooltip.subtext = "点击撤销操作.";
                L.drawLocal.edit.handlers.remove.tooltip.subtext = "点击删除一个元素..";

                this.measure_toolbox.options.edit.featureGroup =  new L.FeatureGroup();
                this.$refs.map.mapObject.addLayer(this.measure_toolbox.options.edit.featureGroup);
                this.measure_toolbox.instance = new L.Control.Draw(this.measure_toolbox.options);
                this.measure_toolbox.instance.main = this.$refs.map.mapObject;
                let that  = this;
                this.$refs.map.mapObject.on(L.Draw.Event.CREATED, function (e) {
                    console.log(e)
                    const type = e.layerType;
                    const layer = e.layer;
                    if (type === L.Draw.Marker.TYPE) {
                        layer.bindPopup('临时marker');
                    } else if (type === L.Draw.CircleMarker.TYPE) {
                        layer.bindPopup('临时圈注点');
                    }
                    that.measure_toolbox.options.edit.featureGroup.addLayer(layer);
                });
                this.$refs.map.mapObject.on('draw:edited', function (e) {
                    var layers = e.layers;
                    layers.eachLayer(function (layer) {
                        //do whatever you want; most likely save back to db
                        console.log(layer)
                    });
                });
                this.measure_toolbox.instance.addTo(this.$refs.map.mapObject);//添加到地图上
                this.measure_toolbox.visible = true;
            },
            //全屏切换
            toggleFullScreen() {


                console.log(this.fullscreen);
                this.fullscreen = !this.fullscreen;

                //右侧信息区域
                var leaflet_right_arr = document.getElementsByClassName('leaflet-right');
                var right_top = leaflet_right_arr[0];
                var right_bottom = leaflet_right_arr[1];
                console.log(leaflet_right_arr);


                //左侧信息区域
                var leaflet_left_arr = document.getElementsByClassName('leaflet-left');
                var left_top = leaflet_left_arr[0];


                //全屏状态
                if(this.fullscreen){
                    right_top.style.right = "0"; //right_top
                    right_top.style.top = "0"; //right_top
                    right_bottom.style.right = "0"; //right_bottom
                    right_bottom.style.bottom = "0"; //right_bottom

                    left_top.style.left = "0"; //left_top
                    left_top.style.top = "0"; //left_top
                }else{
                    right_top.style.right = "19%"; //right_top
                    right_top.style.top = "11%"; //right_top
                    right_bottom.style.right = "19%"; //right_bottom
                    right_bottom.style.bottom = "29%"; //right_bottom

                    left_top.style.left = "19%"; //left_top
                    left_top.style.top = "11%"; //left_top
                }
                let data = {
                    'fullscreen':this.fullscreen
                }
                this.handleMessageToParent("RE1002",data);
            },
            //必须显示热力图图例
            showHeatmapLegend(data){

                this.heatLegend.min = data.min;
                this.heatLegend.max = data.max;
                // regenerate gradient image
                if (data.gradient != this.heatLegend.gradientCfg) {
                    this.heatLegend.gradientCfg = data.gradient;
                    var gradient = this.heatLegend.legendCtx.createLinearGradient(0, 0, 300, 1);
                    for (var key in this.heatLegend.gradientCfg ) {
                        gradient.addColorStop(key, this.heatLegend.gradientCfg[key]);
                    }
                    this.heatLegend.legendCtx.fillStyle = gradient;
                    this.heatLegend.legendCtx.fillRect(0, 0, 300, 10);
                    this.heatLegend.gradientImg = this.heatLegend.legendCanvas.toDataURL();
                }
                console.log("showHeatmapLegend",data)
            },
            markerClick (id ,e) {
                console.log(id,e)
                let data = {
                    'id':id,
                    'lat':e.latlng.lat,
                    'lng':e.latlng.lng,
                }
                this.handleMessageToParent("RE1001",data);
            },
            //中心点改变或者zoom改变来一个
            mapCenterChange (zoom ,e) {
                console.log(zoom,e)
                let data = {
                    'zoom':zoom,
                    'lat':e.lat,
                    'lng':e.lon,
                }
                this.handleMessageToParent("RE1003",data);
            },
            //搜索词回传
            mapSearchCallBack (searchContent) {
                if(searchContent.length <=0){
                    return;
                }
                let data = {
                    'searchContent':searchContent,
                }
                this.handleMessageToParent("RE1004",data);
            },
            zoomUpdated(e){
                console.log("zoomUpdated",e);
                console.log("center",this.mapOptions.center);
                this.mapCenterChange(e ,this.mapOptions.center)
            },
            centerUpdated (center) {
                //console.log("centerUpdated",center);
            },
            boundsUpdated (bounds) {
                //console.log("boundsUpdated",bounds);
            },
            //排序图层
            sortMapLayer(a,b , nameA, nameB){
                /*1 . (a, b) 小于 0 ，那么 a 会被排列到 b 之前；
                * 2 . (a, b) 等于 0 ， a 和 b 的相对位置不变；
                * 3 . (a, b) 大于 0 ， b 会被排列到 a 之前；
                * */
                console.log('sortMapLayer',a,b);
                console.log('sortMapLayer',nameA,nameB);
                return 0;
            },

            //接收信息
            handleMessageFromParent (event) { // 子接收参数
                //console.log(event);
                var data = event.data;
                console.log(data);

                switch (data.cmd) {
                    case '100001':
                        // 热点图数据
                        this.layers.heatmapLayer.heatmapData = data.data;
                        this.showheatmapset(event);
                        break;
                    case '100002':
                        // marker数据
                        this.markers = data.data;
                        break;
                    case '100003':
                        // 地图平移到点
                        this.$refs.map.mapObject.panTo(data.data, {
                            animate: true
                        }) //地图平移，默认就是true，
                        break;
                    case '100004':
                        // 切换主题
                        this.theme.color= data.data;
                        if(this.theme.color == 'green'){
                            this.theme.theme_activecolor = "#3bc96a";
                            this.theme.theme_textcolor = "theme_"+this.theme.color;
                        }else if(this.theme.color == 'blue'){
                            this.theme.theme_activecolor = "#00bdff";
                            this.theme.theme_textcolor = "theme_"+this.theme.color;
                        }else if(this.theme.color == 'gray'){
                            this.theme.theme_activecolor = "#e5eaff";
                            this.theme.theme_textcolor = "theme_"+this.theme.color;
                        }
                        break;
                    case '100005':
                        //console.log('飞线图',data.data.data)
                        // 飞线图数据
                        this.layers.flyLayer.flyData = data.data.data;
                        this.layers.flyLayer.flycfg = data.data.cfg;
                        this.showflymap(event);
                        break;
                    case '100006':
                        //console.log('新增geojson图层',data.data.data)
                        // geojson图层
                        this.showgeojson(data.data);
                        break;
                    case '100007':
                        //设置透明度
                        this.setsalelayer(data.data);
                        break;
                    case '100008':
                        //关闭图层
                        this.setcloselayer(data.data);
                        break;
                    case '100009':
                        //设置基本控件
                        this.setBaseComponent(data.data);
                        break;
                    case '100010':
                        //设置城市搜索框是否显示
                        this.search.searchPanelVisable = data.data.visable;
                        this.setBaseComponent(data.data);
                        break;
                    case '100011':
                        // marker（目标与来源点同时绘制）
                        let destMakerData =  JSON.parse(JSON.stringify(data.data))
                        let srcMakerData =  JSON.parse(JSON.stringify(data.data))
                        //处理src
                        srcMakerData.forEach((item, index) => {
                            item.position = { lat: item.src.src_lat , lng: item.src.src_lon }
                        })
                        //处理dest
                        destMakerData.forEach((item, index) => {
                            item.position = { lat: item.dest.dest_lat , lng: item.dest.dest_lon }
                        })
                        let finalMarkersData = srcMakerData.concat(destMakerData)
                        this.markers = finalMarkersData;
                        break;
                    case 'IN1000'://热力图图例
                        console.log("neibu");
                        this.showHeatmapLegend(data.data)
                        break;
                }
            },
            handleMessageToParent (cmd , data ) { // 子向父传参

                var json = {
                    "cmd":cmd,
                    "data": data
                }
                window.parent.postMessage(json, '*');
            },
            handleMessageToSelf (cmd , data ) { // 子向自己

                var json = {
                    "cmd":cmd,
                    "data": data
                }
                window.parent.postMessage(json, '*');
            }
        },

        created() {
            window.addEventListener('resize', this.getHeight);
            this.getHeight();

        },
        mounted() {
            this.map = this.$refs.map;
            window.addEventListener("message", this.handleMessageFromParent) // 子接收方式二参数
            /*this.$refs.map.mapObject.on('update:zoom', function (zoom,str) {
                console.log(zoom,str)
            });*/

            this.$refs.map.mapObject.on('geosearch/showlocation', function (data) {
                console.log("geosearch",data);
            });
            this.layers.heatmapLayer.heatmapcfg.onExtremaChange = function(data) {
                console.log('热力图****',data);
                var json = {
                    "cmd":"IN1000",
                    "data": data
                }
                window.postMessage(json, '*');
            }
            this.mapCenterChange(this.mapOptions.zoom,this.mapOptions.center)
            this.toggleFullScreen()
            this.heatLegend.legendCanvas = document.createElement('canvas');
            this.heatLegend.legendCtx =this.heatLegend.legendCanvas.getContext('2d');
            //this.heatLegend.gradientImg = document.querySelector('#gradient');
            console.log(this.heatLegend)

            console.log('mounted',this.map);


        },
        computed: {
            control_btns:function(){
                return {
                    btnLayerManager: {
                        'title': "图层管理",
                        'ico': "/static/control_icons/" + this.theme.color + "-navBack.png",
                        'managercss': 'layermanager-tips theme_' + this.theme.color
                    },
                    btnToolBox: {'title':"工具箱",'ico':"/static/control_icons/"+this.theme.color+"-bag.png"} ,
                    btnHeat: {'title':"热力图",'ico':"/static/control_icons/"+this.theme.color+"-mapbtn1.png"} ,
                    btnEye: {'title':"鹰眼图",'ico':"/static/control_icons/"+this.theme.color+"-mapbtn3.png"},
                    btnZoomIn: {'title':"放大",'ico':"/static/control_icons/"+this.theme.color+"-jia.png"},
                    btnZoomOut: {'title':"缩小",'ico':"/static/control_icons/"+this.theme.color+"-jian.png"},
                    btnFullScreen: {'title':"全屏",'ico':"/static/control_icons/"+this.theme.color+"-mapbtn4.png"}
                }
                    ;
            },
            options() {
                return {
                    onEachFeature: this.onEachFeatureFunction
                };
            },
            styleFunction() {
                const fillColor = this.theme.theme_activecolor; // important! need touch fillColor in computed for re-calculate when change fillColor
                const that = this;
                return () => {
                    return  that.layers.geolayers.administrative_regions.style;
                };
            },
            onEachFeatureFunction() {
                return (feature, layer) => {

                    //console.log(feature,layer);
                    /*L.circleMarker(layer.getLatLng(), {
                      radius: 8,
                      fillColor: "#ff7800",
                      color: "#000",
                      weight: 1,
                      opacity: 1,
                      fillOpacity: 0.8
                    });*/
                    /*var shieldIcon = L.icon({
                        iconUrl: '/static/marker-shield.png',
                        iconSize: [40, 40],
                        iconAnchor: [20, 40],
                        popupAnchor: [-3, -76],
                        //shadowUrl: 'my-icon-shadow.png',
                        shadowSize: [68, 95],
                        shadowAnchor: [22, 94]
                    });*/

                    //layer.setIcon(shieldIcon);
                    //console.log('feature',feature);
                    //console.log('layer',layer);
                    //console.log('this',this.layers.geolayers.administrative_regions.cfg.source);

                    let in_text = feature.properties[this.layers.geolayers.administrative_regions.cfg.show_col_name];
                    //tip值
                    let tipText = this.layers.geolayers.administrative_regions.tpl.tipHtml.replaceAll("{{GIS_XZ_NAME}}", in_text);//替换行政区域

                    //弹出值
                    let popText = this.layers.geolayers.administrative_regions.tpl.popHtml.replaceAll("{{GIS_XZ_NAME}}", in_text);//替换行政区域
                    if(tipText!=''){
                        layer.bindTooltip(
                            tipText,
                            { permanent: false, sticky: true }
                        );
                    }
                    if(popText!=''){
                        layer.bindPopup(popText).openPopup();
                    }


                };
            }
        },
    }
</script>

<style lang="stylus" scoped>
    @import 'leaflet/dist/leaflet.css'
    @import "leaflet-draw/dist/leaflet.draw.css"
    @import 'leaflet-minimap/dist/Control.MiniMap.min.css';
    @import "leaflet-draw/dist/leaflet.draw.css"
    .container
        width: 100%
        .mapContainer
            text-align: left
            #map
                height: 100%
                width: 100%
    .custom-control-watermark {
        font-size: 200%;
        font-weight: bolder;
        color: #aaa;
        text-shadow: #555;
    }
    .example-custom-control {
        padding: 0 0.5em;
        border-radius: 0.1em;
        text-shadow: #555;
    }

    /deep/.leaflet-top.leaflet-right  {
        right: 19%;
        top: 11%;
        position :fixed;
    }
    /deep/.leaflet-bottom.leaflet-right  {
        right: 19%;
        bottom: 29%;
        position :fixed;
    }
    /deep/.leaflet-top.leaflet-left  {
        left: 19%;
        top: 11%;
        position :fixed;
    }
    .flex{
        margin-bottom: 10px;
        padding: 20px;
        width: 300px;
        height: 300px;
        background: #f5f5f5;
        border: 1px solid #eee;
        /* flex写法 */
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .cursor_pointer
        cursor:pointer;

    /*右下角控件区域*/
    .right_control
        display: -webkit-flex; /* Safari */
        display: flex;
        flex-direction: column
        .item
            margin-bottom: 10px
            cursor:pointer;

    $focus_color= #38c281;
    $select_backgroud_color= #50a571;
    $select_front_color=#60e8a6;
    .theme_green{
        color:#3bc96a;
    }
    .theme_blue{
        color:#00bdff;
    }
    .theme_gray{
        color:#b6c4ff;
    }
    .leaflet-draw-tooltip {
        position: static !important;
    }
    .layermanager{
        position: relative;
        display : inline-block;
    }
    .layermanager-nav{
        position: relative;
        display : inline-block;
        width:150px;
    }
    .layermanager-tips{
        position : absolute;
        z-index:2;
        margin: 0 auto;
        font-size: 12px;
        display: flex;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        justify-content: center;
        align-items: center;
        cursor:pointer;
        user-select: none;
    }
    .layermanager-img{
        display: block;  width: 100%;  text-align: center;
    }
    .layermanager-img-left{
        position : absolute; /*transform: scale(1.5)*/
        margin-top:6px;
        margin-left:6px;
        cursor: pointer;
    }
    .legend-area
        height :40px;
        width :300px;
        padding:10px;
        background:white;
        outline:3px solid black;
        line-height:1em;
        h4
         margin:0;
         padding:0;
         margin-bottom:5px;
        #min
         float:left;
        #max
         float:right;
        span
         font-size:14px; margin:0; padding:0;
    .legend-loading
        background:white;



</style>